// pages/publish/publish.js

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},

    inputTitle: "",
    inputContent: ""
  },

  onWriteTitle(event) {
    console.log("onWriteTitle", event);
    this.setData({
      inputTitle: event.detail.value
    });
  },

  onWriteContent(event) {
    console.log("onWriteContent", event);
    this.setData({
      inputContent: event.detail.value
    });
  },

  // 点击发布按钮
  onClickPublish(event) {
    console.log("onClickPublish", event);

    const title   = this.data.inputTitle;
    const content = this.data.inputContent;
    if (title == "" || content == "") {
      wx.showToast({
        title: '内容不能为空',
        icon: 'error'
      });
      return;
    }

    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要发布吗？',
      success(res) {
        if (res.confirm) {
          // 用户点击了确定按钮
          console.log('用户点击了确定');
          that.publishArticle();
          wx.navigateBack({
            delta: 2
          });
        } else if (res.cancel) {
          // 用户点击了取消按钮
          console.log('用户点击了取消');
        }
      }
    })
  },

  // 调用云函数 add_article
  publishArticle: function() {
    const userInfo = this.data.userInfo;
    const article = {
      author:       userInfo.realName == "" ? userInfo.nickName : userInfo.realName,
      authorId:     userInfo._id,
      commentCount: 0,
      content:      this.data.inputContent,
      likeCount:    0,
      publishTime:  new Date().getTime(),
      title:        this.data.inputTitle,
      viewCount:    0
    };

    wx.cloud.callFunction({
      name: 'add_article',
      data: {
        article: article
      },
      success: res => {
        console.log("add article success", res);
        return true;
      },
      fail: res => {
        console.log("add article fail", res);
        return false;
      }
    });
  },

  // 生命周期函数--监听页面加载
  onLoad(options) {
    this.setData({
      userInfo: app.globalData.userInfo
    });
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady() { },

  // 生命周期函数--监听页面显示
  onShow() { },

  // 生命周期函数--监听页面隐藏
  onHide() { },

  // 生命周期函数--监听页面卸载
  onUnload() { },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() { },

  // 页面上拉触底事件的处理函数
  onReachBottom() { },

  // 用户点击右上角分享
  onShareAppMessage() { }
})
